//
//  ActionSheetView.m
//  etionUI
//
//  Created by wjxfhxy on 14-7-11.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "XUIActionSheetView.h"

#import "XUIPanelWindow.h"

#define BorderLeftRightMargin      10

#define BorderTopBottomMargin      10

#define BorderButtonMargin          10

//cancelButton与其他Button的距离
#define BorderCancelButtonMargin            20

//按钮的高度
#define ButtonHeight            44

//按钮的大小
#define ButtonImageSize            40

//按钮内部的间隙
#define ButtonBorderMargin      (ButtonHeight - ButtonImageSize)


@interface XUIActionSheetViewBlock : XUIActionSheetView<XUIActionSheetViewDelegate>

@property(nonatomic,assign) void(^clickOtherButton)(NSUInteger clickIndex);

-(id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles;

@end


typedef NS_ENUM(NSUInteger, XUIActionSheetViewButtonType)
{
    XUIActionSheetViewButtonTypeNormal = 0,
    XUIActionSheetViewButtonTypeCancel = 1
};

@interface XUIActionSheetViewButton : UIControl<UIViewExtendDelegate>
{
    UILabel *_textLabel;
    UIImageView *_leftImageView;
    UIImageView *_rightImageView;
    
    UIView *_selectedView;
    UIView *_containView;
}

@property(nonatomic,strong) NSString *text;
@property(nonatomic,strong) UIImage *leftImage;
@property(nonatomic,strong) UIImage *rightImage;

@property(nonatomic,assign) XUIActionSheetViewButtonType type;

@end

@implementation XUIActionSheetViewButton

@synthesize szTag;

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    self.clipsToBounds = YES;
    
    self.backgroundColor = [UIColor whiteColor];
    
    self.layer.borderWidth = 1;
    self.layer.cornerRadius = 5;
    self.layer.borderColor = [UIColor colorWithR:190 G:190 B:190 A:1].CGColor;
    
    [self addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
    [self addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside|UIControlEventTouchCancel];
    
    _containView = [[UIView alloc]initWithFrame:self.bounds];
    _containView.backgroundColor = [UIColor clearColor];
    _containView.userInteractionEnabled = NO;
    [self addSubview:_containView];
    
    _selectedView = [[UIView alloc]initWithFrame:self.bounds];
    _selectedView.bounds = self.bounds;
    _selectedView.backgroundColor = [UIColor grayColor];
    _selectedView.layer.cornerRadius = 5;
    
    _textLabel = [[UILabel alloc]initWithFrame:CGRectMake(ButtonBorderMargin, 0, self.width - ButtonBorderMargin -ButtonBorderMargin, self.height)];
    _textLabel.textColor = [UIColor blackColor];
    _textLabel.textAlignment = NSTextAlignmentCenter;
    _textLabel.font = [UIFont systemFontOfSize:16];
    [_containView addSubview:_textLabel];
    
    return self;
}

-(void)dealloc
{
    self.szTag = nil;
    
    [_textLabel release_mm];
    [_leftImageView release_mm];
    [_rightImageView release_mm];
    [_containView release_mm];
    [_selectedView release_mm];
    
    superdealloc_mm;
}

-(void)touchDown:(id)sender
{
    self.layer.borderWidth = 0;
    [self insertSubview:_selectedView belowSubview:_containView];
}

-(void)touchUp:(id)sender
{
    self.layer.borderWidth = 1;
    [_selectedView removeFromSuperview];
}

-(void)setType:(XUIActionSheetViewButtonType)type
{
    _type = type;
    if(_type == XUIActionSheetViewButtonTypeCancel)
    {
        _textLabel.textColor = [UIColor whiteColor];
        self.backgroundColor = [UIColor colorWithR:255 G:96 B:96 A:1];
        self.layer.borderColor = self.backgroundColor.CGColor;
    }
    else if(_type == XUIActionSheetViewButtonTypeNormal)
    {
        _textLabel.textColor = [UIColor blackColor];
        self.backgroundColor = [UIColor whiteColor];
        self.layer.borderColor = [UIColor colorWithR:190 G:190 B:190 A:1].CGColor;
    }
}

-(void)setText:(NSString *)text
{
    _textLabel.text = text;
}

-(void)setLeftImage:(UIImage *)leftImage
{
    if(_leftImageView == nil)
    {
        _leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(ButtonBorderMargin, ButtonBorderMargin, ButtonImageSize, ButtonImageSize)];
        [_containView addSubview:_leftImageView];
    }
    _leftImageView.image = leftImage;
    
    _textLabel.left = _leftImageView.right + ButtonBorderMargin;
}

-(void)setRightImage:(UIImage *)rightImage
{
    if(_rightImageView == nil)
    {
        _rightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.width - ButtonBorderMargin - ButtonImageSize, ButtonBorderMargin, ButtonImageSize, ButtonImageSize)];
        [_containView addSubview:_rightImageView];
    }
    _rightImageView.image = rightImage;
    
    _textLabel.width = self.width - ButtonBorderMargin - ( _leftImageView != nil ?(_leftImageView.width + ButtonBorderMargin) : 0) - (ButtonBorderMargin + _rightImageView.width )- ButtonBorderMargin ;
}

@end

@interface XUIActionSheetView ()<XUIButtonDelegate,UIGestureRecognizerDelegate>
{
    XUIPanelWindow *_window;
    
    NSString *_title;
    
    NSString *_cancelButtonTitle;
    NSArray *_otherButtonTitles;
    
    NSTextAlignment _textAlignment;
    
    UIView *_containView;
    
    UIScrollView *_scrollView;
    
    XUIActionSheetViewButton *_cancelBtn;
    NSMutableArray *_otherBtns;
    
    id<XUIActionSheetViewDelegate> _delegate;
}
@end

@implementation XUIActionSheetView

@synthesize textAlignment = _textAlignment;

- (id)initWithTitle:(NSString *)title delegate:(id<XUIActionSheetViewDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray*)otherButtonTitles
{
    self = [super initWithFrame:CGRectZero];
    
    _delegate = delegate;
    
    _title = [title retain_mm];
    
    _cancelButtonTitle = [cancelButtonTitle retain_mm];
    
    _otherButtonTitles = [otherButtonTitles retain_mm];
    
    _textAlignment = NSTextAlignmentCenter;
    
    self.backgroundColor = [UIColor colorWithR:0 G:0 B:0 A:0.6];
    
    _containView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    _containView.backgroundColor = [UIColor colorWithR:227 G:227 B:227 A:1];
    [self addSubview:_containView];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    _scrollView.scrollEnabled = NO;
    [_containView addSubview:_scrollView];
    
    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)]
                                   autorelease_mm];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    return self;
}

-(void)dealloc
{
    [_containView release_mm];
    [_scrollView release_mm];
    [_title release_mm];
    [_cancelBtn release_mm];
    [_cancelButtonTitle release_mm];
    [_otherBtns release_mm];
    [_otherButtonTitles release_mm];
    superdealloc_mm;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
}

- (void)show
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    _window = [XUIPanelWindow new];
    _window.responder = self;
    
    self.frame = _window.bounds;
    
    if(_cancelButtonTitle.length >0)
    {
        _cancelBtn = [[XUIActionSheetViewButton alloc]initWithFrame:CGRectMake(BorderLeftRightMargin, _containView.height - BorderTopBottomMargin - ButtonHeight, self.width - BorderLeftRightMargin - BorderLeftRightMargin , ButtonHeight)];
        _cancelBtn.type = XUIActionSheetViewButtonTypeCancel;
        _cancelBtn.text = _cancelButtonTitle;
        [_cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_containView addSubview:_cancelBtn];
    }
    
    if(_otherButtonTitles.count>0)
    {
        CGFloat totalHeight = 0;
        _otherBtns = [NSMutableArray new];
        for(NSUInteger i=0; i<_otherButtonTitles.count; i++)
        {
            NSString *s = _otherButtonTitles[i];
            XUIActionSheetViewButton *btn = [[[XUIActionSheetViewButton alloc]initWithFrame:CGRectMake(0, (ButtonHeight + BorderButtonMargin)* i,self.width - BorderLeftRightMargin - BorderLeftRightMargin , ButtonHeight)] autorelease_mm];
            btn.type = XUIActionSheetViewButtonTypeNormal;
            btn.text = s;
            btn.tag = 1000 + 1 + i;
            [btn addTarget:self action:@selector(otherBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_scrollView addSubview:btn];
            [_otherBtns addObject:btn];
            totalHeight = btn.bottom;
        }
        _scrollView.frame = CGRectMake(BorderLeftRightMargin, 0, self.width - BorderLeftRightMargin - BorderLeftRightMargin, totalHeight);
        _scrollView.contentSize = CGSizeMake(0, _scrollView.height);
    }
    
    CGFloat height = BorderTopBottomMargin + BorderTopBottomMargin;
    height += 0;
    if(_otherButtonTitles.count > 0)
        height += _scrollView.height;
    if(_cancelButtonTitle.length > 0)
    {
        if(_otherButtonTitles.count > 0)
            height += BorderCancelButtonMargin;
        height += ButtonHeight;
    }
    
    if(height > self.height - ([UIDevice isIOS7OrNewer] == YES ? 20 : 0) - 10)
    {
        _scrollView.scrollEnabled = YES;
        CGFloat diff = height - self.height + ([UIDevice isIOS7OrNewer] == YES ? 20 : 0) + 10;
        height -= diff;
        _scrollView.height = _scrollView.contentSize.height - diff;
    }
    
    _containView.frame = CGRectMake(0, self.height - height, self.width, height);
    
    if(_cancelBtn != nil)
        _cancelBtn.bottom = _containView.height - BorderTopBottomMargin;
    
    if(_cancelBtn != nil)
        _scrollView.bottom = _cancelBtn.top - BorderCancelButtonMargin;
    else
        _scrollView.bottom = _containView.height - BorderTopBottomMargin;
    
    
    self.alpha = 0;
    _containView.top = self.height;
    
    keyWindow.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.3 animations:^
    {
         _containView.bottom = self.height;
         self.alpha = 1;
        
    } completion:^(BOOL finished)
    {
        keyWindow.userInteractionEnabled = YES;
    }];
}

-(void)otherBtnClick:(XUIActionSheetViewButton*)sender
{
    NSUInteger i = sender.tag - 1000 -1;
    if([_delegate respondsToSelector:@selector(actionSheetView:clickItemAtIndex:)])
        [_delegate actionSheetView:self clickItemAtIndex:i];
    sender.selected = YES;
    [self close];
}

-(void)cancelBtnClick:(XUIActionSheetViewButton*)sender
{
    if([_delegate respondsToSelector:@selector(clickedCancelButtonOfActionSheetView:)])
        [_delegate clickedCancelButtonOfActionSheetView:self];
    [self close];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint p = [touch locationInView:self];
    if (CGRectContainsPoint(_containView.frame, p) == YES)
        return NO;
    return YES;
}

- (void)tapGestureRecognizer:(UITapGestureRecognizer *)gr
{
    if([_delegate respondsToSelector:@selector(willDismissActionSheetView:)])
        [_delegate willDismissActionSheetView:self];
    [self close];
}

-(void)close
{
    self.superview.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.3 animations:^
    {
        _containView.top = self.height;
        self.alpha = 0;
        
    } completion:^(BOOL finished)
    {
        self.superview.userInteractionEnabled = YES;
        
        [self removeFromSuperview];
        
        ReleaseObj(_window);
    }];
}

+(void)actionSheetViewWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray*)otherButtonTitles show:(void(^)(NSUInteger clickIndex))clickOtherButton
{
    XUIActionSheetViewBlock *act = [[[XUIActionSheetViewBlock alloc] initWithTitle:title cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles] autorelease_mm];
    act.clickOtherButton = clickOtherButton;
    [act show];
}

@end

@implementation XUIActionSheetViewBlock

-(id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles
{
    return [super initWithTitle:title delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles];
}

-(void)setClickOtherButton:(void (^)(NSUInteger))clickOtherButton
{
    Block_release(_clickOtherButton);
    _clickOtherButton = Block_copy(clickOtherButton);
}

-(void)actionSheetView:(XUIActionSheetView *)actionSheetView clickItemAtIndex:(NSUInteger)index
{
    _clickOtherButton(index);
}

-(void)dealloc
{
    Block_release(_clickOtherButton);
    superdealloc_mm;
}

@end
